//
//  shoppingCardController.m
//  pmmSS
//
//  Created by Mac book on 2017/9/26.
//  Copyright © 2017年 WTFSSD. All rights reserved.
//

#import "shoppingCardController.h"
#import "default_Cell.h"

@interface shoppingCardController ()<UITableViewDelegate,UITableViewDataSource,default_CellDelegate>
@property (nonatomic,strong) UIButton *rightButton;

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) UIButton *all_selected_Button, * submit_btn;

@property (nonatomic,strong) UITextField *sum_price_textfield;


@property(nonatomic,strong)NSArray * categorys;
@property(nonatomic,strong)NSMutableArray * dataArray;
@property (strong,nonatomic) NSMutableDictionary *myDic;

@property(nonatomic,assign)NSInteger allPrice;
@property(nonatomic,assign)NSInteger goodsNum;;

@end

static NSString *default_cellId = @"default_Cell";

@implementation shoppingCardController
-(NSMutableArray *)dataArray{

    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
-(NSArray *)categorys{
    if (!_categorys) {
        _categorys = @[

                           @{
                             @"iconImage" : @"list_icon_shop",
                             @"iconTitle" : @"特价处理/批发 工型钢(H型钢)-----02",

                             },

                         @{
                             @"iconImage" : @"list_icon_shop",
                             @"iconTitle" : @"特价处理/批发 工型钢(H型钢)-----03",

                             },



                            @{
                                @"iconImage" : @"list_icon_shop",
                                @"iconTitle" : @"特价处理/批发 工型钢(H型钢)-----02",

                                },

                            @{
                                @"iconImage" : @"list_icon_shop",
                                @"iconTitle" : @"特价处理/批发 工型钢(H型钢)-----03",

                                },

                            @{
                                @"iconImage" : @"list_icon_shop",
                                @"iconTitle" : @"特价处理/批发 工型钢(H型钢)-----02",
           
                                }



                        ];
    }
    return _categorys;
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self setUpNavBar];

}
-(void)setUpNavBar{

    UILabel *title_label = [HMLabel createLabelWithText:@"购物车" andTextColor:[UIColor whiteColor] andBgColor:nil andFont:[UIFont fontWithName:default_fontname size:autoScaleW(18)] andTextAlignment:NSTextAlignmentCenter];
    title_label.frame = CGRectMake(0, 0, 100, 35);

    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"nav_bgimage"] forBarMetrics:UIBarMetricsDefault];

    self.navigationItem.titleView = title_label;

    self.rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.rightButton.frame = CGRectMake(0, 0, 40, 40);
    self.rightButton.tag = 101;
    [self.rightButton setTitle:@"编辑" forState:UIControlStateNormal];
    [self.rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

    [self.rightButton setTitle:@"完成" forState:UIControlStateSelected];
    [self.rightButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];

    [self.rightButton setTitle:@"编辑" forState:UIControlStateDisabled];
    [self.rightButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];

    [self.rightButton addTarget:self action:@selector(clickAllEdit:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *batbutton = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    self.navigationItem.rightBarButtonItem = batbutton;

}
- (void)clickAllEdit:(UIButton *)button{
    button.selected = !button.selected;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.allPrice=0;
    self.goodsNum = 0;

    NSLog(@" view.frame.origin.y ==%f ",GET_FRAME_ORIGINI_Y(self.view));


    [self createTableView];

    [self createFooterView];

    [self loadData];
    // Do any additional setup after loading the view.
}

-(void)createTableView{

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, GET_FRAME_WIDTH(self.view), SCREENH_HEIGHT - autoScaleH(44) - 50 ) style:UITableViewStyleGrouped];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    [self.view addSubview:self.tableView];

    [self.tableView registerClass:[default_Cell class] forCellReuseIdentifier:default_cellId];

}
-(void)createFooterView{

    // TODO : 顶部阴影线
        UIView *lineview =[[UIView alloc]init];
        lineview.backgroundColor = RGB(239, 239, 239);
        [self.view addSubview:lineview];

        [lineview mas_makeConstraints:^(MASConstraintMaker *make) {

            make.bottom.mas_equalTo(autoScaleH(- 43.5) - 50 );
            make.width.mas_equalTo(GET_FRAME_WIDTH(self.view));
            make.height.mas_equalTo(autoScaleH(0.5));

        }];

    // TODO : 按钮
    self.all_selected_Button = [HMButton createButtonWithTitle:nil andTitleColor:nil andBgColor:[UIColor whiteColor] andImage:[UIImage imageNamed:@"shop_normal"] andBgImage:nil andSelecter:@selector(goAllSelect:) andTarget:self andTag:102];
    self.all_selected_Button.clipsToBounds = YES;
    self.all_selected_Button.layer.cornerRadius = autoScaleH(10);
    [self.all_selected_Button setImage:[UIImage imageNamed:@"order_selected"] forState:UIControlStateSelected];
    [self.view addSubview:self.all_selected_Button];

    [self.all_selected_Button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(autoScaleW(10));
        make.bottom.mas_equalTo(autoScaleH(-12) - 50);
        make.width.mas_equalTo(autoScaleW(20));
        make.height.mas_equalTo(autoScaleH(20));
    }];

    // TODO : 全选
    UILabel *all_label  = [ HMLabel createLabelWithText:@"全选" andTextColor:[UIColor blackColor] andBgColor:nil andFont:[UIFont fontWithName:default_fontname size:autoScaleW(16)] andTextAlignment:NSTextAlignmentLeft];
    [self.view addSubview:all_label];

    [all_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(autoScaleW(40));
        make.centerY.mas_equalTo(self.all_selected_Button);
        make.width.mas_equalTo(autoScaleW(35));
        make.height.mas_equalTo(autoScaleH(20));
    }];

    // TODO : 合计
    UILabel *sum_label  = [ HMLabel createLabelWithText:@"合计" andTextColor:[UIColor blackColor] andBgColor:nil andFont:[UIFont fontWithName:default_fontname size:autoScaleW(16)] andTextAlignment:NSTextAlignmentLeft];
    [self.view addSubview:sum_label];

    [sum_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(autoScaleW(140));
        make.centerY.mas_equalTo(self.all_selected_Button);
        make.width.mas_equalTo(autoScaleW(35));
        make.height.mas_equalTo(autoScaleH(20));
    }];

    // TODO : ￥￥￥￥￥￥￥
    UILabel *icon_price_label  =[ HMLabel createLabelWithText:@"￥" andTextColor:RGBA(252,74,0,1) andBgColor:nil andFont:[UIFont fontWithName:default_fontname size:autoScaleW(12)] andTextAlignment:NSTextAlignmentLeft];
    [self.view addSubview:icon_price_label];

    [icon_price_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(autoScaleW(188));
        make.centerY.mas_equalTo(self.all_selected_Button);
        make.width.mas_equalTo(autoScaleW(10));
        make.height.mas_equalTo(autoScaleH(17));
    }];

    // TODO : 总数量---number
     self.sum_price_textfield = [HMTextField createTextFieldWithText:@"0" andpLlaceholder:nil andTextColor:RGBA(252,74,0,1) andBgColor:nil andFont:nil andTextAlignment:NSTextAlignmentLeft andTextFieldViewMode:UITextFieldViewModeNever];

     [self.view addSubview:self.sum_price_textfield];

    [self.sum_price_textfield mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(autoScaleW(200));
        make.centerY.mas_equalTo(self.all_selected_Button);
        make.width.mas_equalTo(autoScaleW(80));
        make.height.mas_equalTo(autoScaleH(17));
    }];

    // TODO : 结算---按钮
    self.submit_btn = [HMButton createButtonWithTitle:@"结算(0)" andTitleColor:nil andBgColor:RGBA(73, 157, 245, 1) andImage:nil andBgImage:nil andSelecter:@selector(clickAllEdit:) andTarget:self andTag:103];

    [self.view addSubview:self.submit_btn];
    [self.submit_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(0);
        make.centerY.mas_equalTo(self.all_selected_Button);
        make.width.mas_equalTo(autoScaleW(104));
        make.height.mas_equalTo(autoScaleH(44));
    }];


}
#pragma mark : UITableViewDelegate,UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{



    return self.categorys.count;

}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    default_Cell *cell = [tableView dequeueReusableCellWithIdentifier:default_cellId];

      cell.selectionStyle =UITableViewCellSelectionStyleNone;

      [cell reloadWithModel:self.dataArray[indexPath.row]];

    cell.delegate = self;

    return cell;


}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return autoScaleH(100);

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return autoScaleH(40);

}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{

    return autoScaleH(10);

}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, autoScaleH(40))];

    headerView.backgroundColor = [UIColor whiteColor];

    UILabel *headerlabel = [ HMLabel createLabelWithText:@"钢材市场" andTextColor:[UIColor blackColor] andBgColor:nil andFont:[UIFont fontWithName:default_fontname size:autoScaleW(14)] andTextAlignment:NSTextAlignmentLeft];


    [headerView addSubview:headerlabel];
    [headerlabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.centerY.mas_equalTo(headerView);
        make.left.mas_equalTo(autoScaleW(30));
        make.width.mas_equalTo(autoScaleW(150));
        make.height.mas_equalTo(autoScaleH(20));

    }];


    return headerView;

}

#pragma mark -- 实现加减按钮点击代理事件
/**
 *  实现加减按钮点击代理事件
 *
 *  @param cell 当前单元格
 *  @param flag 按钮标识，11 为减按钮，12为加按钮
 */
-(void)btnClick:(UITableViewCell *)cell andFlag:(int)flag{
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    switch (flag) {
        case 101:
        {
            shoppingCardModel *model = self.dataArray[index.row];
            if (model.selectState)            {
                model.selectState = NO;
            }else {
                model.selectState = YES;
            }

        }
            break;
        case 102:
        {
            //做加法
            shoppingCardModel *model = self.dataArray[index.row];
            if (model.count > 0)
            {
                model.count ++;
            }
        }
            break;
        case 103:
        {    //先获取到当期行数据源内容，改变数据源内容，刷新表格

            //做减法
            //先获取到当期行数据源内容，改变数据源内容，刷新表格
            shoppingCardModel *model = self.dataArray[index.row];
            if (model.count > 1)
            {
                model.count --;

            }
            //刷新当前行
            //[self.goodsTableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        default:
            break;
    }
    //刷新表格
    [self.tableView reloadData];

    //计算总价
    [self totalPrice];

}
#pragma mark -- 计算价格
-(void)totalPrice
{
    //遍历整个数据源，然后判断如果是选中的商品，就计算价格（单价 * 商品数量）
    for ( int i =0; i<self.dataArray.count; i++)    {
        shoppingCardModel *model = [self.dataArray objectAtIndex:i];
        if (model.selectState)
        {
            self.allPrice +=  model.price * model.count ;//[model.goodsPrice intValue];

        }
    }

    //给总价文本赋值
    self.sum_price_textfield.text = [NSString stringWithFormat:@"%ld 元",(long)self.allPrice];

    //每次算完要重置为0，因为每次的都是全部循环算一遍
    self.allPrice = 0;
    self.goodsNum = 0;
}
//结算
//-(void)goStatement{
//    NSInteger total=[self.settlementView.sumLab.text integerValue];
//    if (total>0) {
//        StatementViewController *statementVC=[[StatementViewController alloc]init];
//        statementVC.price=total;
//        [self.navigationController pushViewController:statementVC animated:YES];
//
//    }
//}
//全选
-(void)goAllSelect:(UIButton *)button{
    //判断是否选中，是改成否，否改成是，改变图片状态
    button.selected = !button.selected;
    if (button.tag)    {
        [button setImage:[UIImage imageNamed:@"order_selected"] forState:UIControlStateSelected];

    }else{
        [button setImage:[UIImage imageNamed:@"shop_normal"] forState:UIControlStateNormal];
    }
    //改变单元格选中状态
    for (int i=0; i<self.dataArray.count; i++)
    {
        shoppingCardModel *model = [self.dataArray objectAtIndex:i];
        model.selectState = button.selected;
    }
    //计算价格
    [self totalPrice];
    //刷新表格
    [self.tableView reloadData];

}

-(void)loadData{

 self.myDic = [[NSMutableDictionary alloc]init];

    for (int i = 0; i < self.categorys.count; i++) {



            NSDictionary * dic = [self.categorys objectAtIndex:i];

        //修改字典数据


            [self.myDic addEntriesFromDictionary:dic];


            [self.myDic setObject:[NSNumber numberWithBool:NO] forKey:@"selectState"];

            [self.myDic setObject:[NSNumber numberWithInt:100] forKey:@"price"];

             [self.myDic setObject:[NSNumber numberWithInt:1] forKey:@"count"];
            //

            shoppingCardModel *model = [shoppingCardModel initWithDic:self.myDic];

            [self.dataArray addObject:model];

            NSLog(@"self.dataArray == %lu",(unsigned long)self.dataArray.count);
        }




}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
